<template>
  <div class="package-set">
    <a-form ref="formRef" :colon="false" autocomplete="off" :label-col="{ style: { width: '130px' } }" lableWidth>
      <a-form-item name="saleSwitch" label="自定义开关">
        <div class="form-item">
          <a-switch
            v-model:checked="formState.saleSwitch"
            :unCheckedValue="0"
            :checkedValue="1"
            un-checked-children="关闭"
            checked-children="启用"
          />
          <div class="item-info">
            <info-circle-outlined class="info-icon" />
            <span class="info-describe">注意：仅在开关开启后，此部分的自定义的内容才生效</span>
          </div>
        </div>
      </a-form-item>
      <div class="uploadLogo uploadAlipay">
        <a-form-item name="payQr" label="微信/支付宝收款码">
          <a-upload
            name="customerlogo"
            list-type="picture-card"
            accept="image/png"
            class="avatar-uploader"
            :show-upload-list="false"
            :disabled="alipayLoading"
            :before-upload="beforeUpload"
            :customRequest="handleAliPayCodeRequest"
          >
            <template v-if="formState.payQr">
              <img :src="formState.payQr" alt="微信/支付宝收款码" :width="126" :height="126" />
              <close-circle-filled class="file-close" @click.stop="formState.payQr = ''" />
            </template>
            <div class="inner-info" v-else style="width: 126px; height: 126px">
              <loading-outlined v-if="alipayLoading"></loading-outlined>
              <upload-outlined v-else></upload-outlined>
              <div class="ant-upload-text">上传图片</div>
            </div>
          </a-upload>
          <div class="upload-info">
            <info-circle-outlined class="info-icon" />
            只支持png格式，384*384px
          </div>
        </a-form-item>
      </div>

      <a-form-item name="feeModel" label="售卖方式">
        <a-select v-model:value="formState.feeModel" placeholder="请选择" style="width: 200px" disabled>
          <a-select-option value="SCORE"> 按次数计费 </a-select-option>
          <a-select-option value="CYCLE"> 按周期计费 </a-select-option>
        </a-select>
      </a-form-item>
      <template v-if="formState.feeModel == 'CYCLE'">
        <a-form-item name="freeTimes" label="免费次数">
          <div class="form-item">
            <a-input-number
              class="item-number"
              :precision="0"
              placeholder="最高每日免费次数不得高于100次"
              v-model:value="formState.freeTimes"
              :min="0"
              :max="100"
            />
            <span class="item-unit">次</span>
          </div>
        </a-form-item>
        <a-form-item name="freeLimit" label="免费期限">
          <div class="form-item">
            <a-input-number
              class="item-number"
              :precision="0"
              placeholder="最高免费试用时间不得超过180天"
              v-model:value="formState.freeLimit"
              :min="0"
              :max="180"
            />
            <span class="item-unit">日</span>
          </div>
        </a-form-item>
      </template>

      <a-form-item label="" class="table-item">
        <div class="item-empty"></div>
        <div class="form-table drawer-table-empty">
          <a-table
            :scroll="{ y: 'calc(100vh - 366px)' }"
            bordered
            :columns="packageColumns"
            :dataSource="formState.feeModel === 'CYCLE' ? formState.cyclePackageVOS : formState.scorePackageVOS"
            :pagination="false"
          >
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.dataIndex === 'packageName'">
                <EllipsisTooltip :title="record.packageName" :width="130">
                  {{ record.packageName }}
                </EllipsisTooltip>
              </template>
              <template v-else-if="column.dataIndex === 'packageType'">
                <span v-if="record.packageType === 'corp'">企业</span>
                <span v-else-if="record.packageType === 'human'">个人</span>
                <span v-else></span>
              </template>
              <template v-else-if="column.dataIndex === 'goodDesc'">
                <EllipsisTooltip :title="record.goodDesc">
                  {{ record.goodDesc }}
                </EllipsisTooltip>
              </template>
              <template v-else-if="column.dataIndex === 'channelPrice'">
                <a-input-number
                  class="table-input"
                  :controls="false"
                  v-model:value="record.channelPrice"
                  @change="record.channelPrice = parseFloat(record.channelPrice).toFixed(2)"
                  :min="0"
                  :max="9999999"
                />
              </template>
              <template v-else-if="column.dataIndex === 'settlePrice'">
                <a-input-number
                  class="table-input"
                  :controls="false"
                  v-model:value="record.settlePrice"
                  @change="record.settlePrice = parseFloat(record.settlePrice).toFixed(2)"
                  :min="0"
                  :max="9999999"
                />
              </template>
              <template v-else-if="column.dataIndex === 'isShow'">
                <div class="check-box" @click="checkChange(record, 'isShow')">
                  <div class="table-check" v-if="record.isShow == 1 || record.isShow == 2"></div>
                  <div class="table-uncheck" v-else></div>
                </div>
              </template>
            </template>
          </a-table>
        </div>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, unref, watch, onMounted } from 'vue'
import { operateActionType } from '@/types/enum'
import { message, Divider } from 'ant-design-vue'
import { InfoCircleOutlined, CloseCircleFilled, UploadOutlined, LoadingOutlined } from '@ant-design/icons-vue'
import EllipsisTooltip from '@/components/EllipsisTooltip/index.vue'
import type { UploadProps } from 'ant-design-vue'
import { cloneDeep, debounce } from 'lodash-es'
import { obsUpAndDownload } from '@/utils/file/obs'
import { userStore } from '@/store/modules/user'
import ObsClient from 'esdk-obs-browserjs/src/obs'
import api from '@/api'

const { updateChannelConfig, uploadLogo, generateChannelLoginUrlOrDownloadUrl, getPackageConfig, saveOrUpdate } = api
const emit = defineEmits(['operateSuccess', 'register'])
const userModule = userStore()

const props = defineProps({
  packageSetData: {
    type: Object,
    default: () => {}
  },
  operateType: {
    type: String,
    default: operateActionType.EDIT
  }
})

const alipayLoading = ref<boolean>(false)
let obsClient: any
const packageColumns = [
  {
    title: '套餐名称',
    align: 'center',
    width: 140,
    dataIndex: 'packageName'
  },
  {
    title: '类型',
    align: 'center',
    width: 80,
    dataIndex: 'packageType'
  },
  {
    title: '套餐说明',
    align: 'center',
    dataIndex: 'goodDesc'
  },
  {
    title: '标准价（元）',
    align: 'center',
    width: 100,
    dataIndex: 'orgAmt'
  },
  {
    title: '渠道售价（元）',
    align: 'center',
    width: 120,
    dataIndex: 'channelPrice'
  },
  {
    title: '结算价（元）',
    align: 'center',
    width: 120,
    dataIndex: 'settlePrice'
  },
  {
    title: '套餐是否显示',
    align: 'center',
    width: 100,
    dataIndex: 'isShow'
  }
]

const formState = reactive<any>({
  feeModel: 'SCORE',
  freeLimit: null,
  freeTimes: null,
  cyclePackageVOS: [],
  scorePackageVOS: [],
  payQr: '',
  saleSwitch: 0
})

const currentUserType = computed(() => userModule.userInfo?.userType)

const getInitData = () => {
  let packageSetData = cloneDeep(props.packageSetData)
  formState.feeModel = packageSetData.feeModel
  formState.freeLimit = packageSetData.freeLimit
  formState.freeTimes = packageSetData.freeTimes
  formState.cyclePackageVOS = packageSetData.cyclePackageVOS || []
  formState.scorePackageVOS = packageSetData.scorePackageVOS || []
  formState.payQr = packageSetData.payQr
  formState.saleSwitch = packageSetData.saleSwitch
}

// 校验文件格式
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('请上传图片文件')
    return false
  }
  return true
}
const obsFileName = 'bpaiChannel'
const getObsClient = async () => {
  let res = await uploadLogo({
    dir: `psy-public/${import.meta.env.VITE_OBS_DIR}/UI/${obsFileName}`
  })
  let result = res.result
  obsClient = new ObsClient({
    access_key_id: result.access, // 你的ak
    secret_access_key: result.secret, // 你的sk
    security_token: result.securitytoken,
    server: result.server // 你的endPoint
  })
}

// 支付宝付款码上传
const handleAliPayCodeRequest = async (options: any) => {
  try {
    alipayLoading.value = true
    await getObsClient()
    options.obsFileName = obsFileName
    formState.payQr = await obsUpAndDownload(obsClient, options)
    alipayLoading.value = false
  } catch (error) {
    alipayLoading.value = false
  }
}

onMounted(() => {
  getInitData()
})

const checkChange = (dataRecord: any, type: string) => {
  if (dataRecord[type] == 2) {
    message.warning('该套餐不可取消勾选')
    return
  }
  dataRecord[type] = dataRecord[type] == 1 ? 0 : 1
}
// 数据显示格式化
const dayFormat = (value: number | null) => {
  return value || value == 0 ? value : '--'
}
// 数据提交
const submitData = () => {
  if (formState.feeModel == 'CYCLE') {
    if (!formState.freeTimes && formState.freeTimes != 0) {
      message.warning('请输入免费次数')
      return false
    }
    if (!formState.freeLimit && formState.freeLimit != 0) {
      message.warning('请输入免费期限')
      return false
    }
  }
  let packageList = formState.feeModel == 'CYCLE' ? formState.cyclePackageVOS : formState.scorePackageVOS
  console.info(packageList)
  let flag = true
  if (packageList && packageList.length) {
    for (let i = 0; i < packageList.length; i++) {
      if (packageList[i].isShow == 1 || packageList[i].isShow == 2) {
        flag = false
        if (!packageList[i].channelPrice && packageList[i].channelPrice != 0) {
          message.warning('渠道售价不能为空')
          return false
        }
        if (!packageList[i].settlePrice && packageList[i].settlePrice != 0) {
          message.warning('结算价不能为空')
          return false
        }
      }
    }
    if (flag) {
      message.warning('至少勾选一个套餐显示')
      return false
    }
  }
  return cloneDeep(formState)
}

// 输出组件的方法，让外部组件可以调用
defineExpose({
  submitData
})
</script>
<style lang="less" scoped>
.package-set {
  .form-item {
    display: flex;
    align-items: center;
    .item-number {
      width: 230px;
    }
    .item-input {
      width: 408px;
    }
    .item-info {
      display: flex;
      align-items: center;
      margin-left: 24px;
      color: #c0c0c0;
      font-size: 12px;
      .info-icon {
        margin-right: 4px;
      }
    }
  }
  :deep(.table-item) {
    margin-bottom: 0;
    .ant-form-item-control-input-content {
      display: flex;
      .item-empty {
        width: 130px;
        flex-shrink: 0;
      }
    }
  }
  :deep(.form-table) {
    overflow: hidden;
    .ant-table-tbody > tr.ant-table-row:hover > td,
    .ant-table-tbody > tr > td.ant-table-cell-row-hover {
      background: #fff;
    }
    .ant-table .ant-table-container .ant-table-tbody > tr > td {
      padding: 5px 5px;
      line-height: 22px;
    }
    .ant-table.ant-table-bordered > .ant-table-container {
      border-left: none;
    }
    .ant-table-body > table {
      margin-bottom: 24px;
    }
    .ant-table-header > table,
    .ant-table-body > table {
      border-left: 1px solid #e0e1e6;
    }

    .ant-table-thead > tr > th {
      color: #555d6f;
    }
    .table-input {
      width: 100%;
      .ant-input-number-input {
        text-align: center;
      }
    }
    .check-box {
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      .table-check {
        width: 14px;
        height: 14px;
        background: #4aa353;
        border-radius: 50%;
        position: relative;
        &::after {
          content: '';
          position: absolute;
          width: 6px;
          height: 9px;
          border: 2px solid #fff;
          border-top: none;
          border-left: none;
          left: 4px;
          top: 1px;
          transform: rotate(45deg);
        }
      }
      .table-uncheck {
        width: 14px;
        height: 14px;
        border-radius: 50%;
        border: 1px solid #cdcdcd;
      }
      &.check-view {
        cursor: default;
        .table-uncheck {
          display: none;
        }
      }
    }
  }
  .item-title {
    margin-bottom: 24px;
  }
  .item-unit {
    color: #1b2134;
    line-height: 17px;
    font-size: 12px;
    margin-left: 8px;
  }
  .ant-switch-checked {
    background-color: #4aa353;
  }
}
.uploadLogo {
  margin: 24px 0;
  padding: 0 8px;
  &.uploadAlipay {
    padding: 0;
    margin: 0;
  }
  :deep(.ant-image-img) {
    background-color: #f3f4f8;
    width: 100%;
    height: 100%;
  }
  .avatar-uploader {
    position: relative;
    .file-close {
      font-size: 12px;
      color: #c0c0c0;
      position: absolute;
      right: 2px;
      top: 0;
      cursor: pointer;
      z-index: 999;
    }
  }

  :deep(.ant-form-item-no-colon) {
    height: 38px;
    align-items: center;
  }
  // .avatar-uploader > .ant-upload {
  //   width: 240px;
  //   height: 38px;
  // }
  :deep(.ant-upload) {
    position: relative;
    width: auto;
    height: auto;
    .inner-info {
      width: 240px;
      height: 38px;
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    img {
      background-color: #f3f4f8;
    }
  }
  .ant-upload-select-picture-card i {
    font-size: 12px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-left: 5px;
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #535d71;
  }
  :deep(.ant-form-itm-no-colon) {
    width: 61px;
    height: 22px;
    font-size: 12px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #192236;
    line-height: 22px;
  }
  :deep(.file-upload) {
    width: 242px;
    height: 40px;
    background: #ffffff;
    border-radius: 2px;
    border: 1px solid #cdcdcd;
  }
  .upload-info {
    color: #c0c0c0;
    font-size: 12px;
    .info-icon {
      font-size: 14px;
      margin-right: 4px;
    }
  }
}
</style>
